package com.gxj.study.shopdemo.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.DefaultSliderView;
import com.gxj.study.shopdemo.Contants;
import com.gxj.study.shopdemo.R;
import com.gxj.study.shopdemo.WareDetailActivity;
import com.gxj.study.shopdemo.adapter.BaseAdapter;
import com.gxj.study.shopdemo.adapter.CategoryAdapter;
import com.gxj.study.shopdemo.adapter.WaresAdapter;
import com.gxj.study.shopdemo.adapter.decoration.DividerGridItemDecoration;
import com.gxj.study.shopdemo.adapter.decoration.DividerItemDecortion;
import com.gxj.study.shopdemo.bean.Banner;
import com.gxj.study.shopdemo.bean.Category;
import com.gxj.study.shopdemo.bean.Page;
import com.gxj.study.shopdemo.bean.Wares;
import com.gxj.study.shopdemo.http.OkHttpHelper;
import com.gxj.study.shopdemo.http.SpotsCallBack;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class CategoryFragment extends BaseFragment {
    @ViewInject(R.id.recyclerView_category)
    private RecyclerView mRecyclerView;

    @ViewInject(R.id.recyclerView_wares)
    private RecyclerView mRecyclerViewWares;

    @ViewInject(R.id.refresh_layout)
    private MaterialRefreshLayout mRefreshLayout;

    @ViewInject(R.id.slider)
    private SliderLayout mSlideLayout;

    private CategoryAdapter mCategoryAdapter;
    private WaresAdapter mWaresAdapter;

    private OkHttpHelper mHttpHelper = OkHttpHelper.getmInstance();

    private int currPage = 1;
    private int totalPage = 1;
    private int pageSize = 10;
    private long category_id = 0;

    private static final int STATE_NORMAL = 0;
    private static final int STATE_REFRESH = 1;
    private static final int STATE_MORE = 2;

    private int state = STATE_NORMAL;


    //    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                             Bundle savedInstanceState) {
//        View view = inflater.inflate(R.layout.fragment_category, container, false);
//        ViewUtils.inject(this, view);
//
//
//        return view;
//    }
    @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.fragment_category, container, false);
    }

    @Override
    public void init() {
        requestCategoryData();
        requestBannerData();

        initRefreshLayout();
    }


    private void initRefreshLayout() {

        mRefreshLayout.setLoadMore(true);
        mRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                refreshData();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {

                if (currPage <= totalPage)
                    loadMoreData();
                else {
                    mRefreshLayout.finishRefreshLoadMore();
                }
            }
        });
    }

    private void refreshData() {
        currPage = 1;
        state = STATE_REFRESH;
        requestWares(category_id);
    }

    private void loadMoreData() {
        currPage = ++currPage;
        state = STATE_MORE;
        requestWares(category_id);
    }

    private void requestCategoryData() {
        mHttpHelper.get(Contants.API.CATEGORY_LIST, new SpotsCallBack<List<Category>>(getActivity()) {

            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onSuccess(Response response, List<Category> categories) {
                showCategoryData(categories);

                if (categories != null && categories.size() > 0) {
                    category_id = categories.get(0).getId();
                    requestWares(category_id);
                }
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
    }

    private void showCategoryData(List<Category> categories) {
        mCategoryAdapter = new CategoryAdapter(getActivity(), categories);
        mCategoryAdapter.setmOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Category category = mCategoryAdapter.getItem(position);

                category_id = category.getId();
                currPage = 1;
                state = STATE_NORMAL;

                requestWares(category_id);
            }
        });
        mRecyclerView.setAdapter(mCategoryAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecortion(getActivity(), DividerItemDecortion.VERTICAL_LIST));
    }

    private void requestBannerData() {
        String url = Contants.API.BANNER + "?type=1";

        mHttpHelper.get(url, new SpotsCallBack<List<Banner>>(getActivity()) {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onSuccess(Response response, List<Banner> banners) {
                showSlideViews(banners);
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
    }

    private void showSlideViews(List<Banner> banners) {
        if (banners != null) {
            for (Banner banner : banners) {
                DefaultSliderView sliderView = new DefaultSliderView(this.getActivity());
                sliderView.image(banner.getImgUrl());
                sliderView.description(banner.getName());
                sliderView.setScaleType(BaseSliderView.ScaleType.Fit);
                mSlideLayout.addSlider(sliderView);
            }
        }
        mSlideLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        mSlideLayout.setCustomAnimation(new DescriptionAnimation());
        mSlideLayout.setPresetTransformer(SliderLayout.Transformer.Default);
        mSlideLayout.setDuration(3000);
    }

    private void requestWares(long category_id) {
        String url = Contants.API.WARES_LIST + "?categoryId=" + category_id + "&curPage=" + currPage + "&pageSize=" + pageSize;

        mHttpHelper.get(url, new SpotsCallBack<Page<Wares>>(getActivity()) {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onSuccess(Response response, Page<Wares> waresPage) {
                currPage = waresPage.getCurrentPage();
                totalPage = waresPage.getTotalPage();

                showWaresData(waresPage.getList());
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
    }

    private void showWaresData(List<Wares> wares) {
        switch (state) {
            case STATE_NORMAL:
                if (mWaresAdapter == null) {
                    mWaresAdapter = new WaresAdapter(getActivity(), wares);
                    mWaresAdapter.setmOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            Wares wares1 = mWaresAdapter.getItem(position);
                            Intent intent = new Intent(getActivity(),WareDetailActivity.class);

                            intent.putExtra(Contants.WARE,wares1);
                            startActivity(intent);
                        }
                    });
                    mRecyclerViewWares.setAdapter(mWaresAdapter);
                    mRecyclerViewWares.setLayoutManager(new GridLayoutManager(getContext(), 2));
                    mRecyclerViewWares.setItemAnimator(new DefaultItemAnimator());
//                    mRecyclerViewWares.addItemDecoration(new DividerGridItemDecoration(getContext()));
                } else {
                    mWaresAdapter.clearData();
                    mWaresAdapter.addData(wares);
                }
                break;
            case STATE_REFRESH:
                mWaresAdapter.clearData();
                mWaresAdapter.addData(wares);

                mRecyclerViewWares.scrollToPosition(0);
                mRefreshLayout.finishRefresh();
                break;
            case STATE_MORE:
                mWaresAdapter.addData(mWaresAdapter.getDatas().size(), wares);
                mRecyclerViewWares.scrollToPosition(mWaresAdapter.getDatas().size());
                mRefreshLayout.finishRefresh();
                break;
        }
    }
}